//app.js
const req = require('utils/requests.js')

App({
  onLaunch: function () {
  },
  globalData: {
    userInfo: null,
    album: {},
    loginCallbacks:[]
  },
  getUserInfo:function(callback) {
    var that = this
    if (this.globalData.userInfo == null) {
      if (this.globalData.loginCallbacks.length == 0) {
        wx.login({
          success: res => {
            var userInfo = {}
            userInfo['code'] = res.code
            wx.getUserInfo({
              withCredentials: true,
              complete: function(res) {
                console.log(res)
                req.POST({
                  action: '/wxapi/login/',
                  data: userInfo,
                  showError: true,
                  complete: function (code, msg, data) {
                    if (code == 0) {
                      wx.setStorageSync('token', data.token)
                      wx.setStorageSync('userInfo', data)
                    }
                    that.globalData.loginCallbacks.forEach(function (item) {
                      item(code, data)
                    });
                  }
                })
              }
            })
          }
        })
      } 
      this.globalData.loginCallbacks.push(callback)
    } else {
      callback(0, this.globalData.userInfo)
    }
  },
  topPage:function() {
    var pages = getCurrentPages()
    return pages[pages.length - 1]
  },
  prePage:function() {
    var pages = getCurrentPages()
    return pages[pages.length - 2]
  }
})